package com.action;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpSession;

import com.hdb.*;
import com.hdb.dao.Types;
import com.util.OrderItem;

import com.util.Cart;
import org.apache.struts2.convention.annotation.*;


/**
 * @author aszer
 */

/**
 * @author aszer
 *
 */

@ParentPackage("default")
@Namespace("/order")
@Results({
        @Result(name = "succeed", location = "/common/succeed.jsp"),
        @Result(name = "myCart", location = "/view/order/myCart.jsp"),
        @Result(name = "confirm", location = "/view/order/orderConfirm.jsp"),
        @Result(name = "submit", location = "/view/order/orderSubmit.jsp"),
        @Result(name = "orderDetail", location = "/view/order/orderDetail.jsp"),
        @Result(name = "myOrder", location = "/view/order/myOrder.jsp"),
})
@InterceptorRef("userStack")/*设置用户过滤器*/
public class OrderAction extends BasicAction {
    private int goodId;
    private int goodCount;
    private static int iNum = 0;
    private int orderId;
    private DB db;
    private String message;
    private String path;
    private String fromDate;
    private String toDate;
    private String orderEmail;
    private int orderPayType;
    private int payType;

    /*
     * 将点卡添加到购物车
     * 使用goodsId获得点卡信息，并添加到session中的cart中
     */
    @Action("addToCart")
    public String addToCart() {
        TGood good = db.goodDAO.findById(goodId);
        if (good.getGoodInventory() < goodCount) {
            setMessage("库存不足,无法购买");
            setPath("good/goodDetail.action?goodId=" + Integer.toString(goodId));
            return "succeed";
        }
        Cart cart = getCart();
        cart.goodAdd(good, goodCount);
        setPath("order/myCart.action");
        return "succeed";
    }
    /*查看购物车*/
    @Action(value = "myCart")
    public String myCart() {
        return "myCart";
    }

    /*订单信息*/
    @Action("orderConfirm")
    public String orderConfirm() {
        return "confirm";
    }


    /*
     * 提交订单
     * 交由员工或管理员处理
     */
    @Action("orderSubmit")
    public String orderSubmit() {
        HttpSession session = getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        TUser user = (TUser) session.getAttribute("user");
        for (OrderItem orderItem : cart.getItems().values()) {
            TGood good = db.goodDAO.findById(orderItem.getGood().getGoodId());
            if (good.getGoodInventory() < orderItem.getCount()) {
                setMessage("商品: [" + good.getGoodName() + "] 库存不足.无法提交订单");
                setPath("order/myCart.action");
                return "succeed";
            }
        }

        TMyOrder order = new TMyOrder();
        order.setOrderNumber(new SimpleDateFormat("yyyyMMddhhmmss").format(new Date())
                + Integer.toString(1000 + (int) (Math.random() * 100))
                + Integer.toString(++iNum));
        order.setOrderDate(new Timestamp(new Date().getTime()));
        order.setOrderState(Types.order.Submit);//已提交未受理状态
        order.setUserId(user.getUserId());
        order.setOrderPrice(cart.getTotalPrice());
        order.setOrderPayType(orderPayType);
        order.setOrderEmail(orderEmail);
        if (!db.orderDAO.save(order)) {
            setMessage("订单保存出错");
            setPath("/index.action");
            return "succeed";
        }
        order = db.orderDAO.findOne("orderNumber", order.getOrderNumber());
        for (OrderItem orderItem : cart.getItems().values()) {
            TOrderGood og = new TOrderGood();
            og.setOrderId(order.getOrderId());
            og.setGoodId(orderItem.getGood().getGoodId());
            og.setCount(orderItem.getCount());
            if (!db.orderGoodDAO.save(og)) {
                //保存出错,还原已保存信息
                db.orderGoodDAO.delete("orderId", order.getOrderId());
                db.orderDAO.delete("orderId", order.getOrderId());
                setMessage("订单物品保存出错");
                setPath("/index.action");
                return "succeed";
            }
        }
        //更新库存
        for (OrderItem orderItem : cart.getItems().values()) {
            db.goodInventoryUpdate(orderItem.getGood().getGoodId(), orderItem.getCount());
        }
        cart.getItems().clear();
        getRequest().put("order", order);
        return "submit";
    }

    /*
     * 用户取消自己的订单
     */
    @Action("orderDel")
    public String orderDel() {
        TMyOrder order = db.orderDAO.findById(orderId);

        TUser user = getUser();
        if (order == null || order.getUserId() != user.getUserId()) {
            setMessage("订单不存在");
        }
        if (order.getOrderState() != 0) {
            setMessage("不能取消已受理订单");
        } else {
            order.setOrderState(Types.order.Delete);
            //撤销库存修改
            List<Object[]> goodList = db.orderGoodDAO.join(db.goodDAO, "goodId", "orderId", order.getOrderId(), 0, 100);
            for (Object[] g : goodList) {
                TOrderGood og = (TOrderGood) g[0];
                TGood good = (TGood) g[1];
                db.goodInventoryRestore(good.getGoodId(), og.getCount());
            }
            if (!db.orderDAO.attach(order)) {
                setMessage("取消出错");
            }
        }
        setPath("order/myOrder.action?userId=" + user.getUserId());
        return "succeed";
    }
    /*
     * 用户查看自己的订单
     */
    @Action("myOrder")
    public String myOrder() {
        int[] p = getP();
        TUser user = getUser();
        List orderList = db.findOrder(user.getUserId(), p[0], p[1]);
        getRequest().put("orderList", orderList);
        getPLink(orderList.size());
        return "myOrder";
    }

    /*
     * 查看订单详情
     */
    @Action("orderDetail")
    public String orderDetail() {
        int[] p = getP();
        List<OrderItem> orderItemList = new ArrayList<>();
        TMyOrder order = db.orderDAO.findById(orderId);
        if (order == null || order.getUserId() != getUser().getUserId()) {
            getRequest().put("orderItemList", orderItemList);
            getPLink(orderItemList.size());
            return "orderDetail";
        }
        List<Object[]> goodlist = db.orderGoodDAO.join(db.goodDAO, "goodId", "orderId", orderId, p[0], p[1]);
        for (Object[] item : goodlist) {
            OrderItem oi = new OrderItem((TGood) item[1], ((TOrderGood) item[0]).getCount());
            orderItemList.add(oi);
        }
        getRequest().put("orderItemList", orderItemList);
        getPLink(orderItemList.size());
        return "orderDetail";
    }

    public int getOrderPayType() {
        return orderPayType;
    }

    public void setOrderPayType(int orderPayType) {
        this.orderPayType = orderPayType;
    }

    public String getFromDate() {
        return fromDate;
    }

    public void setFromDate(String fromDate) {
        this.fromDate = fromDate;
    }

    public String getToDate() {
        return toDate;
    }

    public void setToDate(String toDate) {
        this.toDate = toDate;
    }

    public int getGoodId() {
        return goodId;
    }

    public void setGoodId(int goodsId) {
        this.goodId = goodsId;
    }

    public int getGoodCount() {
        return goodCount;
    }

    public void setGoodCount(int goodCount) {
        this.goodCount = goodCount;
    }

    public int getOrderId() {
        return orderId;
    }

    public void setOrderId(int orderId) {
        this.orderId = orderId;
    }

    public DB getDb() {
        return db;
    }

    public void setDb(DB db) {
        this.db = db;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getOrderEmail() {
        return orderEmail;
    }

    public void setOrderEmail(String orderEmail) {
        this.orderEmail = orderEmail;
    }

    public int getPayType() {
        return payType;
    }

    public void setPayType(int payType) {
        this.payType = payType;
    }
}
